<template>
  <div class="lottery-numbers">
    <!-- 接口请求加载动画 -->
    <div v-if="isLoading" class="api-loading">
      <div class="loading-spinner"></div>
      <p>正在获取数据...</p>
    </div>

    <div v-else>
      <div class="number-display">
        <div class="front-numbers">
          <h3>前区号码</h3>
          <div class="numbers">
            <span v-for="num in generatedNumbers?.front" :key="num" class="number ball-front">
              {{ num }}
            </span>
          </div>
        </div>

        <!-- 仅当有后区配置时显示后区号码 -->
        <div v-if="hasBack" class="back-numbers">
          <h3>后区号码</h3>
          <div class="numbers">
            <span v-for="num in generatedNumbers?.back" :key="num" class="number ball-back">
              {{ num }}
            </span>
          </div>
        </div>
      </div>
      <button class="generate-btn" @click="handleCalculate" :disabled="isCalculating || isLoading">
        {{ isCalculating ? '生成中...' : '生成号码' }}
      </button>

      <!-- 进度条区域（简化为固定显示） -->
      <div v-if="isCalculating" class="progress-container">
        <div class="progress-info">
          <span>正在生成号码</span>
          <span class="progress-percentage">100%</span>
        </div>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: '100%' }"></div>
        </div>
        <div class="progress-time">
          已用时: {{ formatTime(elapsedTime) }}
        </div>
      </div>

      <!-- 结果弹窗（简化为显示生成结果） -->
      <div v-if="matchingResult" class="result-modal">
        <div class="modal-content">
          <h3>号码生成结果</h3>
          <div class="result-item">
            <span class="result-label">状态:</span>
            <span>生成成功</span>
          </div>
          <div class="result-item">
            <span class="result-label">耗时:</span>
            <span>{{ formatTime(matchingResult.totalTime) }}</span>
          </div>
          <div class="result-item">
            <span class="result-label">前区号码:</span>
            <span>{{ matchingResult.numbers?.front.join(', ') }}</span>
          </div>

          <!-- 仅当有后区时显示后区结果 -->
          <div v-if="hasBack" class="result-item">
            <span class="result-label">后区号码:</span>
            <span>{{ matchingResult.numbers?.back.join(', ') }}</span>
          </div>

          <button class="close-btn" @click="matchingResult = null">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineProps, ref, computed, onMounted } from 'vue'
import { generateRandomNumbers } from '@/api/api'

const props = defineProps({
  config: {
    type: Object,
    required: true
  },
  type: {
    type: String,
    required: true
  }
})

// 计算属性：根据配置判断是否有后区
const hasBack = computed(() => {
  return props.config.hasBack !== undefined ? props.config.hasBack : true
})

const generatedNumbers = ref({
  front: [],
  back: [] // 初始化空数组，避免null
})
const isCalculating = ref(false)
const isLoading = ref(false)  // 接口请求加载状态
const elapsedTime = ref(0)
const matchingResult = ref(null)
const startTime = ref(0)
const timer = ref(null)
const emit = defineEmits(['onMatchComplete'])

// 初始化生成空号码，避免null
onMounted(() => {
  generatedNumbers.value = {
    front: [],
    back: []
  }
})

// 格式化时间显示 (毫秒 -> mm:ss)
const formatTime = (ms) => {
  const seconds = Math.floor(ms / 1000)
  const minutes = Math.floor(seconds / 60)
  return `${minutes.toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`
}

// 调用接口生成号码 - 添加加载状态
const generateNumbersFromApi = async () => {
  try {
    isLoading.value = true
    console.log(props.type, 'type');

    const result = await generateRandomNumbers({
      type: props.type
    })

    if (result && result.code === 20000) {
      const data = result.data || {}
      return {
        front: data.front || [],
        back: hasBack.value ? (data.back || []) : []
      }
    }
    throw new Error('生成号码失败: ' + (result?.msg || '未知错误'))
  } catch (error) {
    console.error('生成号码出错:', error)
    throw error
  } finally {
    isLoading.value = false
  }
}

// 处理计算逻辑（修复耗时统计）
const handleCalculate = async () => {
  try {
    isCalculating.value = true
    elapsedTime.value = 0
    matchingResult.value = null
    startTime.value = Date.now()

    // 1. 启动计时器（每次点击重新初始化，确保从0开始）
    timer.value = setInterval(() => {
      elapsedTime.value = Date.now() - startTime.value
    }, 100)

    // 2. 从接口获取号码（耗时会被计时器实时统计）
    const initialNumbers = await generateNumbersFromApi()
    generatedNumbers.value = initialNumbers

    // 3. 停止计时器并计算总耗时（关键修复：此时再停止，确保统计完整）
    clearInterval(timer.value)
    const totalTime = Date.now() - startTime.value

    // 4. 赋值弹窗数据，此时totalTime已准确计算
    matchingResult.value = {
      success: true,
      totalTime, // 传入准确的总耗时
      numbers: {
        front: initialNumbers.front || [],
        back: hasBack.value ? (initialNumbers.back || []) : []
      }
    }

    // 触发完成事件
    emit('onMatchComplete', {
      numbers: matchingResult.value.numbers,
      success: true,
      totalTime
    })

  } catch (error) {
    console.error('生成失败:', error)
    alert('获取号码失败: ' + error.message)
    // 错误时也要停止计时器，避免内存泄漏
    clearInterval(timer.value)
  } finally {
    isCalculating.value = false
    // 移除finally中的计时器停止，避免提前终止
  }
}
</script>

<style scoped>
/* 样式部分无修改，保持原代码不变 */
.lottery-numbers {
  text-align: center;
  padding: 2rem;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
}

.api-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem 1rem;
  color: #666;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #42b983;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.number-display {
  display: flex;
  justify-content: center;
  gap: 2rem;
  margin-bottom: 2rem;
  flex-wrap: wrap;
}

.front-numbers,
.back-numbers {
  flex: 1;
  min-width: 250px;
  padding: 1rem;
  border-radius: 6px;
  background-color: #f9f9f9;
}

h3 {
  color: #666;
  margin-bottom: 1rem;
  font-size: 1.2rem;
}

.numbers {
  display: flex;
  gap: 0.8rem;
  justify-content: center;
  flex-wrap: wrap;
  margin-bottom: 1rem;
}

.number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 45px;
  height: 45px;
  border-radius: 50%;
  color: white;
  font-weight: bold;
  font-size: 1.1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.number:hover {
  transform: scale(1.05);
}

.ball-front {
  background-color: #42b983;
}

.ball-back {
  background-color: #3498db;
}

.generate-btn {
  padding: 0.8rem 2rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-top: 1rem;
}

.generate-btn:hover {
  background-color: #359e75;
}

.generate-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  opacity: 0.8;
}

.progress-container {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: #f5f5f5;
  border-radius: 6px;
  text-align: left;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
  color: #666;
  font-size: 0.95rem;
}

.progress-percentage {
  font-weight: bold;
  color: #42b983;
}

.progress-bar {
  height: 10px;
  background-color: #e0e0e0;
  border-radius: 5px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

.progress-fill {
  height: 100%;
  background-color: #42b983;
  transition: width 0.3s ease;
}

.progress-time {
  color: #666;
  font-size: 0.9rem;
  text-align: right;
}

.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 1rem;
}

.modal-content {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-content h3 {
  color: #333;
  margin-top: 0;
  text-align: center;
}

.result-item {
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #eee;
}

.result-label {
  display: inline-block;
  width: 100px;
  font-weight: bold;
  color: #666;
}

.close-btn {
  display: block;
  margin: 1.5rem auto 0;
  padding: 0.7rem 2rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.close-btn:hover {
  background-color: #359e75;
}

@media (max-width: 768px) {
  .number-display {
    flex-direction: column;
    gap: 1rem;
  }

  .number {
    width: 40px;
    height: 40px;
    font-size: 1rem;
  }

  .generate-btn {
    width: 100%;
    padding: 0.7rem;
  }
}
</style>